package idv.cjcat.stardust.common.math;
	import org.w3c.dom.Element;

import idv.cjcat.stardust.common.xml.XMLBuilder;
	
	/**
	 * This class generates uniformly distrubuted random numbers.
	 */
	public class UniformRandom extends Random {
		
		/**
		 * The expected value of the random number.
		 */
		public double center;
		/**
		 * The variation of the random number.
		 * 
		 * <p>
		 * The range of the generated random number is [center - radius, center + radius].
		 * </p>
		 */
		public double radius;
		
		public UniformRandom(double center, double radius) {
			this.center = center;
			this.radius = radius;
		}
		public UniformRandom(double center) {
			this.center = center;
			this.radius = 0;
		}
		public UniformRandom() {
			this.center = 0.5;
			this.radius = 0;
		}
		
		@Override 
		public final double random() {
			if (radius!=0) return radius * 2 * (Math.random() - 0.5) + center;
			else return center;
		}
		
		@Override 
		public void setRange(double lowerBound, double upperBound) {
			double diameter = upperBound - lowerBound;
			radius = 0.5 * diameter;
			center = lowerBound + radius;
		}
		
		@Override 
		public double[] getRange(){
			double[] range = {center - radius, center + radius};
			return range;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		@Override
		public String getXMLTagName() {
			return "UniformRandom";
		}
		
		@Override
		public Element toXML() {
			Element xml = super.toXML();
			
			xml.setAttribute("center", "" + center);
			xml.setAttribute("radius", "" + radius);
			
			return xml;
		}
		
		@Override
		public void parseXML(Element xml, XMLBuilder builder) {
			super.parseXML(xml, builder);
			
			if (xml.hasAttribute("center")) center = Float.parseFloat(xml.getAttribute("center"));
			if (xml.hasAttribute("radius")) radius = Float.parseFloat(xml.getAttribute("radius"));
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
